import _ from 'lodash'
import axios from 'axios'
import Promise from 'promise'

let Api = {}
let methodsWithParams = ['get', 'head', 'delete']
Api.setConfig = function () {}
Api.apiRespLogic = null
Api.apiErrorHandler = null
Api.http = function (url, method, data, params) {
  if (!data) {
    data = {}
  }
  let conf = {}
  let isQueryMethod = false
  if (_.indexOf(methodsWithParams, method) > -1) {
    isQueryMethod = true
    conf.params = data
  } else if (params) {
    conf.params = params
  }
  Api.setConfig && Api.setConfig(conf)
  return (isQueryMethod ? axios[method](url, conf) : axios[method](url, data, conf)).then(resp => {
    if (!Api.apiRespLogic) throw Error('AjaxService must set apiRespLogic function')
    return Api.apiRespLogic(resp)
  }).catch(err => {
    Api.apiErrorHandler && Api.apiErrorHandler(err)
    return Promise.reject(err)
  })
}
export default Api
